package com.huanf.media.service.impl;

import com.alibaba.nacos.client.config.utils.ContentUtils;
import com.alibaba.nacos.common.http.param.MediaType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanf.domain.dto.UploadFileParamsDto;
import com.huanf.domain.dto.UploadFileResultDto;
import com.huanf.domain.entity.MediaProcess;
import com.huanf.media.mapper.MediaFilesMapper;
import com.huanf.media.mapper.MediaProcessMapper;
import com.huanf.media.service.MediaFilesService;
import com.huanf.domain.dto.QueryMediaParamsDto;
import com.huanf.domain.entity.MediaFiles;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.xuecheng.base.enums.CourseEnum;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.base.model.RestResponse;
import io.minio.*;

import io.minio.errors.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 媒资信息(MediaFiles)表服务实现类
 *
 * @author makejava
 * @since 2024-04-15 22:18:03
 */
@Service
@Slf4j
public class MediaFilesServiceImpl extends ServiceImpl<MediaFilesMapper, MediaFiles> implements MediaFilesService {

    @Autowired
    MediaFilesMapper mediaFilesMapper;

    @Autowired
    MinioClient minioClient;

    @Autowired
    MediaFilesService mediaFilesService;

    @Value("${minio.bucket.files}")
    private String bucket_mediafiles;

    @Value("${minio.bucket.videofiles}")
    private String bucket_videofiles;

    @Autowired
    MediaProcessMapper mediaProcessMapper;

    @Override
    public MediaFiles getFileById(String mediaId) {
        MediaFiles mediaFiles = mediaFilesMapper.selectById(mediaId);
        return mediaFiles;
    }

    @Override
    public PageResult<MediaFiles> queryMediaFiels(Long companyId, PageParams pageParams, QueryMediaParamsDto queryMediaParamsDto) {

        //构建查询条件对象
        LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();

        //分页对象
        Page<MediaFiles> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<MediaFiles> pageResult = mediaFilesMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<MediaFiles> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<MediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return mediaListResult;

    }

    @Override
    public UploadFileResultDto uploadFile(Long companyId, UploadFileParamsDto uploadFileParamsDto, String localFilePath, String objectName) {
        //将文件上传到minio
        //首先从上传文件的DTO信息里拿到文件名
        String filename = uploadFileParamsDto.getFilename();
        //拿到文件的扩展名
        String extension = filename.substring(filename.lastIndexOf("."));
        String mimeType = getMimeType(extension);
        //根据不同的文件的类型上传至不同的桶bucket , 比如视频文件上传到video桶，图片上传到image桶
        //这里选择从配置文件中读取桶名称
        String fileFolder = getFileFolder(true, true, true);
        //拿到md5值
        String md5 = getFileMd5(new File(localFilePath));
        //拼接object对象名为 路径+md5值+文件扩展名
        //存储到minio的文件名，目录+文件名+后缀
        if(StringUtils.isEmpty(objectName)){
            objectName =  fileFolder + md5 + extension;
        }

        boolean result = addMediaFilesTOMinIo(objectName, mimeType, localFilePath, bucket_mediafiles);
        if (!result){
            XueChengPlusException.cast("文件上传失败");
        }
        //将文件信息保存到数据库
        MediaFiles mediaFiles = mediaFilesService.addMediaFilesToDb(companyId, md5, uploadFileParamsDto, bucket_mediafiles, objectName);
        if (mediaFiles==null){
            XueChengPlusException.cast("文件上传后保存信息失败");
        }
        UploadFileResultDto uploadFileResultDto = new UploadFileResultDto();
        BeanUtils.copyProperties(mediaFiles,uploadFileResultDto);
        return uploadFileResultDto;
    }

    /**
     * 将文件上传到minio
     * @param objectName
     * @param mimeType
     * @param localFilePath
     * @param bucket
     * @return
     */
    public boolean addMediaFilesTOMinIo(String objectName, String mimeType, String localFilePath, String bucket){
        try {
            UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .filename(localFilePath)
                    .contentType(mimeType)
                    .build();
            minioClient.uploadObject(uploadObjectArgs);
            log.debug("文件上传成功,bucket:{},objectName:{},错误信息:{}",bucket,objectName);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件上传失败,bucket:{},objectName:{},错误信息:{}",bucket,objectName,e.getMessage());
        }
        return false;
    }

    //根据扩展名获取mineType
    private String getMimeType(String extension){
        if (extension==null){
           extension = "";
        }
        //根据扩展名去查找mineType对应的一张字典表（比如传 "jpg"，它会返回一个 ContentInfo 对象，其中封装着 image/jpeg），如果是“”或者“xyz”等不存在的扩展名则返回null
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        //application/octet-stream 是一种通用的“二进制流”类型，表示“我不知道这是什么，就当做一堆字节”——在 HTTP 里，这是最保险的默认值
        String mimeType = MediaType.APPLICATION_OCTET_STREAM;
        if (extensionMatch!=null){
            //如果有值，就把它的 getMimeType() 拿出来，覆盖掉默认值
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }
    /**
     * 自动生成目录
     * @param year  是否包含年
     * @param month 是否包含月
     * @param day   是否包含日
     * @return
     */
    private String getFileFolder(boolean year, boolean month, boolean day) {
        StringBuffer stringBuffer = new StringBuffer();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = dateFormat.format(new Date());
        String[] split = dateString.split("-");
        if (year) {
            stringBuffer.append(split[0]).append("/");
        }
        if (month) {
            stringBuffer.append(split[1]).append("/");
        }
        if (day) {
            stringBuffer.append(split[2]).append("/");
        }
        return stringBuffer.toString();
    }
    private String getFileMd5(File file) {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            String fileMd5 = DigestUtils.md5Hex(fileInputStream);
            return fileMd5;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @description 将文件信息添加到数据库
     * @param companyId  机构id
     * @param fileMd5  文件md5值，也就是文件名(不包含后缀)
     * @param uploadFileParamsDto  上传文件的信息
     * @param bucket  桶
     * @param objectName 对象名称
     */
    @Transactional
    public MediaFiles addMediaFilesToDb(Long companyId, String fileMd5, UploadFileParamsDto uploadFileParamsDto, String bucket, String objectName) {
        //将文件信息保存到数据库
        MediaFiles mediaFiles = new MediaFiles();
        MediaFiles mediaFilesData = mediaFilesMapper.selectById(fileMd5);
        if (mediaFilesData == null){
            //将DTO中的数据拷贝到实体类中
            BeanUtils.copyProperties(uploadFileParamsDto,mediaFiles);
            //文件id
            mediaFiles.setId(fileMd5);
            //机构id
            mediaFiles.setCompanyId(companyId);
            //桶
            mediaFiles.setBucket(bucket);
            //filePath
            mediaFiles.setFilePath(objectName);
            //file_id md5值
            mediaFiles.setFileId(fileMd5);
            //url
            mediaFiles.setUrl("/"+bucket+"/"+objectName);
            //上传时间
            mediaFiles.setCreateDate(LocalDateTime.now());
            //状态 1：正常 0：不展示
            mediaFiles.setStatus("1");
            //审核状态
            mediaFiles.setAuditStatus(CourseEnum.MINIO_AUDIT_YES.getCode());
            //插入数据库
            int insert = mediaFilesMapper.insert(mediaFiles);
            if (insert <= 0){
                log.debug("文件信息保存失败，bucket：{},objectName:{}",bucket,objectName);
                return null;
            }
            //===========记录待处理任务===============//
            //向MediaProcess插入记录
            //通过mineType判断如果是avi视频则写入待处理任务
            mediaFilesService.addWaitingTask(mediaFiles);
            return mediaFiles;
        }
        return mediaFiles;
    }
    @Override
    public void addWaitingTask(MediaFiles mediaFiles){
        //获取文件的mimeType
        String filename = mediaFiles.getFilename();
        //拿到文件的扩展名
        String extension = filename.substring(filename.lastIndexOf("." ));
        String mimeType = getMimeType(extension);
        if (mimeType.equals("video/x-msvideo")){
            MediaProcess mediaProcess = new MediaProcess();
            BeanUtils.copyProperties(mediaFiles,mediaProcess);
            //状态 未处理
            mediaProcess.setStatus("1");
            mediaProcess.setCreateDate(LocalDateTime.now());
            mediaProcess.setFailCount("0");
            mediaProcess.setUrl(null);
            mediaProcessMapper.insert(mediaProcess);
        }
    }

    @Override
    public RestResponse<Boolean> checkFile(String fileMd5)  {
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
        //如果数据库不存在，直接返回false表示不存在
        if (mediaFiles == null){
            return RestResponse.success(false);
        }
        //若数据库中存在，根据数据库中的文件信息，则继续判断bucket中是否存在
        try {
            InputStream inputStream = minioClient.getObject(GetObjectArgs
                    .builder()
                    .bucket(mediaFiles.getBucket())
                    .object(mediaFiles.getFilePath())
                    .build());
            if (inputStream !=null){
                return RestResponse.success(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResponse.success(false);
    }

    @Override
    public RestResponse<Boolean> checkChunk(String fileMd5, int chunkIndex) {
        // 获取分块目录,根据md5值得到分块文件的路径 为md5的前两位加上chunk作为存放分块文件的路径
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        String chunkFilePath = chunkFileFolderPath + chunkIndex;
        try {
            GetObjectArgs objectArgs = GetObjectArgs.builder()
                    .bucket(bucket_videofiles)
                    .object(chunkFilePath)
                    .build();
            GetObjectResponse response = minioClient.getObject(objectArgs);
            if (response !=null){
                //文件已经存在
                return RestResponse.success(true);
            }
        } catch (Exception e) {
           e.printStackTrace();
        }
        return RestResponse.success(false);
    }

    @Override
    public RestResponse uploadChunk(String fileMd5, int chunk, String localChunkPath) {
        //分块文件路径
        String mimeType = getMimeType(null);
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5)+chunk;
        boolean b = addMediaFilesTOMinIo(chunkFileFolderPath, mimeType, localChunkPath, bucket_videofiles);
        if (!b){
            return RestResponse.validfail("上传分块文件失败",false);
        }
        //上传成功
        return RestResponse.success(true );
    }

    @Override
    public RestResponse mergeChunks(Long companyId, String fileMd5, int chunkTotal, UploadFileParamsDto uploadFileParamsDto) {
        //分块文件目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        //找到分块文件调用minio的sdk进行文件合并
        List<ComposeSource> sources = Stream.iterate(0, i -> ++i).limit(chunkTotal).map(i -> ComposeSource.builder().bucket(bucket_videofiles).object(chunkFileFolderPath + i).build()).collect(Collectors.toList());
        //合并后文件路径的objectName
        String fileName = uploadFileParamsDto.getFilename();
        String extension = fileName.substring(fileName.lastIndexOf("." ));
        String objectName = getFilePathByMd5(fileMd5, extension);

        ComposeObjectArgs objectArgs = ComposeObjectArgs.builder()
                .bucket(bucket_videofiles)
                .object(objectName)
                .sources(sources)
                .build();
        try {
            minioClient.composeObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("合并文件出错，bucket:{},objectName:{}，错误信息{}",bucket_videofiles,objectName,e.getMessage());
            return RestResponse.validfail("合并文件出错",false);
        }
        //校验合并后的文件和源文件是否一致,视频上传才算成功
        //===========校验合并后的和源文件是否一致，视频上传才成功===========
        //先下载合并后的文件
        File file = downloadFileFromMinIO(bucket_videofiles, objectName); //这里非常消耗网络，前端请求执行到这行时会直接自动断掉，如果是线上的话就不要校验了
        try(FileInputStream fileInputStream = new FileInputStream(file)){
            //计算合并后文件的md5
            String mergeFile_md5 = DigestUtils.md5Hex(fileInputStream);
            //比较原始md5和合并后文件的md5
            if(!fileMd5.equals(mergeFile_md5)){
                return RestResponse.validfail("文件校验失败",false);
            }
            //文件大小
            uploadFileParamsDto.setFileSize(file.length());
        }catch (Exception e) {
            return RestResponse.validfail("文件校验失败",false);
        }
        //将文件信息入库
        MediaFiles mediaFiles = mediaFilesService.addMediaFilesToDb(companyId, fileMd5, uploadFileParamsDto, bucket_videofiles, objectName);
        if (mediaFiles == null){
            return RestResponse.validfail("文件信息保存失败",false);
        }
        //清理分块文件
        clearChunkFiles(chunkFileFolderPath, chunkTotal);

        return RestResponse.success(true);
    }

    private String getChunkFileFolderPath(String fileMd5) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + "chunk" + "/";
    }
    /**
     * 根据MD5和文件扩展名，生成文件路径，例 /2/f/2f6451sdg/2f6451sdg.mp4
     * @param fileMd5       文件MD5
     * @param extension     文件扩展名
     * @return
     */
    private String getFilePathByMd5(String fileMd5, String extension) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + fileMd5 + extension;
    }
    /**
     * 清除分块文件
     * @param chunkFileFolderPath 分块文件路径
     * @param chunkTotal 分块文件总数
     */
    private void clearChunkFiles(String chunkFileFolderPath,int chunkTotal) {
        Iterable<DeleteObject> objects = Stream.iterate(0, i -> ++i).limit(chunkTotal).map(i -> new DeleteObject(chunkFileFolderPath + i)).collect(Collectors.toList());
        ;
        RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder().bucket(bucket_videofiles).objects(objects).build();
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(removeObjectsArgs);
        //要想真正删除
        results.forEach(f -> {
            try {
                DeleteError deleteError = f.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    /**
     * 从minio下载文件
     * @param bucket 桶
     * @param objectName 对象名称
     * @return 下载后的文件
     */
    public File downloadFileFromMinIO(String bucket,String objectName){
        //临时文件
        File minioFile = null;
        FileOutputStream outputStream = null;
        try{
            InputStream stream = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .build());
            //创建临时文件
            minioFile=File.createTempFile("minio", ".merge");
            outputStream = new FileOutputStream(minioFile);
            IOUtils.copy(stream,outputStream);
            return minioFile;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

